package com.supermap.application.controller;

import com.alibaba.fastjson.JSONObject;
import com.supermap.application.common.*;
import com.supermap.application.entity.TMacroIdenmeta;
import com.supermap.application.entity.TMacroPeriod;
import com.supermap.application.entity.TMacroTablemeta;
import com.supermap.application.service.MacroPeriodService;
import com.supermap.application.service.MacroTableinfoService;
import com.supermap.application.service.MacroTablemetaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName MacroTablemetaController
 * @Description TODO
 * @Author HEKE
 * @Date 2019/2/24 21:56
 */

@Controller
@RequestMapping(value = {"/macro","/service/macro"})
public class MacroTablemetaController {

    @Autowired
    private MacroTablemetaService macroTablemetaService;

    @Autowired
    private MacroTableinfoService macroTableinfoService;

    @Autowired
    private MacroPeriodService macroPeriodService;


    /**
     * 查询综合指标
     * @param reportType
     * @param parid
     * @param regionLevel
     * @param matmids
     * @return
     */
    @RequestMapping(value = "/Types/{Type}/Items", method = RequestMethod.GET)
    @ResponseBody
    public List<TMacroTablemeta> getIndicators(@PathVariable("Type") int reportType, int parid, int regionLevel,
                                               @RequestBody int[] matmids) {
        List<TMacroTablemeta> tablemetas = new ArrayList<>();
        List<TMacroTablemeta> re = new ArrayList<>();
        if(matmids!=null && matmids.length>0){
            tablemetas = macroTablemetaService.getByMatmids(matmids);//跨表的指标ID组查询
        }else{
            tablemetas = macroTablemetaService.listRoot(parid, regionLevel, reportType);//单表指标查询
        }

        for(TMacroTablemeta tablemeta:tablemetas){
            re.add(tablemeta);
        }

        return re;
    }

    /**
     * 过滤两端无数据的报告期时间
     * @param macroQuery
     * @return
     */
    @RequestMapping(value = "/Data/Query/hasRanks",method = RequestMethod.POST)
    @ResponseBody
    public TimeRank getTimeRanks(@RequestBody MacroQuery macroQuery) {
        String tableName = macroTablemetaService.recogniseTableName(macroQuery.getRegionLevel());
        //获取表下的指标
        Map<String, Object> map = this.filterIndicators(macroQuery);
        String indicatorStr = map.get("selIndCode").toString();//当前表下的全部（或选中）指标CODE
        List<TMacroPeriod> macroPeriods = macroTableinfoService.getPeriodByMatmids(macroQuery.getMatmids());
        TimeRank timeRank = macroTableinfoService.calculateTimeRank(macroPeriods, macroQuery.getReportType());

        timeRank = macroTableinfoService.trimTimeRank(timeRank,tableName,indicatorStr,macroQuery.getReportType());

        return timeRank;
    }

    //过滤选中的指标
    private Map<String,Object> filterIndicators(MacroQuery macroQuery){
        List<TMacroTablemeta> selIndicators = new ArrayList<TMacroTablemeta>();//指定查询指标数组
        String indicatorStr = "";//指定查询指标字符串
        List<TMacroTablemeta> allIndicators = null;
        //查询父表ID 或 所选指标ID集下全部指标
        if(macroQuery.getMatmids() == null || macroQuery.getMatmids().length<1) {
            allIndicators = macroTablemetaService.getByParidAndreportType(Integer.parseInt(macroQuery.getParid()), macroQuery.getReportType());
        }else{
            allIndicators = macroTablemetaService.getByMatmids(macroQuery.getMatmids());
        }

        List<String> indicatorCodes = macroQuery.getIndicatorCodes();//指定查询指标CODE
        if (!indicatorCodes.equals(null) && indicatorCodes.size() > 0) {
            for (int i=0,size=indicatorCodes.size(); i<size; i++) {
                indicatorStr += "'" + indicatorCodes.get(i) + "',";
                for (TMacroTablemeta t : allIndicators) {
                    if (t.getIdenCode().equals(indicatorCodes.get(i))) {
                        selIndicators.add(t);
                        break;
                    }
                }
            }
        } else {
            selIndicators = allIndicators;
            for (TMacroTablemeta t : allIndicators) {
                indicatorStr += "'" + t.getIdenCode() + "',";
            }
        }
        //枚举分组指标 也要纳入其中
        for(TMacroTablemeta selInd:selIndicators){
            List<TMacroIdenmeta> groupInds = macroTablemetaService.findAllGroupInd(selInd);
            if(null == groupInds||groupInds.size()==0){
                continue;
            }
            for(TMacroIdenmeta groupInd: groupInds){
                indicatorStr  += "'" + groupInd.getIdenCode() + "',";
            }
        }

        if (indicatorStr != "") {
            indicatorStr = indicatorStr.substring(0, indicatorStr.length() - 1);
        }
        Map<String,Object> reMap = new HashMap<>();
        reMap.put("selInd",selIndicators);
        reMap.put("selIndCode",indicatorStr);
        return reMap;
    }


    @RequestMapping(value = "/data/findAllYear", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject findByReportType(Integer reportType){
        JSONObject periodByReportType = this.macroPeriodService.findPeriodByReportType(reportType);
        return periodByReportType;
    }


    /**
     * 综合数据条件查询 获取三视图数据【统一入口】
     *
     * @param macroQuery 综合查询对象
     * @return
     */
    @RequestMapping(value = "/data/queryext", method = RequestMethod.GET)
    @ResponseBody
    public MacroDataResult queryAll(HttpServletRequest request, @RequestBody MacroQuery macroQuery) {
        //查询数据表名（分级存储）
        String tableName = macroTablemetaService.recogniseTableName(macroQuery.getRegionLevel());
        //构建报告期时段
        int reportType = macroQuery.getReportType();
        if(macroQuery.getMatmids() != null && macroQuery.getMatmids().length>0){
            //根据指标ID查询所属报告期类型
            TMacroTablemeta oneTMT = macroTablemetaService.getOne(macroQuery.getMatmids()[0]);
            reportType = oneTMT.getReportType();
            macroQuery.setReportType(reportType);
        }
        List<TMacroPeriod> perids = PeriodSupport.createPeriodByTimeRank(reportType, macroQuery.getTimeRank());
        List result = new ArrayList<>();
        //获取表下的指标
        Map<String,Object> map = this.filterIndicators(macroQuery);
        List<TMacroTablemeta> selIndicators = (List) map.get("selInd");//指定指标（含子指标）的元数据
        String indicatorStr = map.get("selIndCode").toString();//当前表下的全部（或选中）指标CODE
        if(indicatorStr.equals("")) {
            System.out.println("表节点"+macroQuery.getParid()+"/报告期类型"+macroQuery.getReportType()+"下设置指标空！");
            return null;
        }
        //查询综合指标数据
        String groupIdencode = macroQuery.getIdenCodes();
        String[] groupIdenArr = null;
        if(groupIdencode != null && groupIdencode != ""){
            groupIdenArr = groupIdencode.split(",");
            for(int i = 0; i < groupIdenArr.length ;i++){
                groupIdenArr[i] = "'" + groupIdenArr[i] + "'";
            }
            indicatorStr = StringUtils.join(groupIdenArr,",");
        }
        result = macroTablemetaService.queryAllData(tableName, macroQuery, indicatorStr);//获取全部指标数据
        result = macroTablemetaService.formatPrecision(result,selIndicators,false);//根据指标精度将数据格式化
        //预处理区域##
        Region[] regions = macroTablemetaService.preHandleRegion(macroQuery.getCatalog(), macroQuery.getRegions(), macroQuery);
        //封装综合数据结果对象
        MacroDataResult re = macroTablemetaService.formatAllData(result, perids, selIndicators, regions,groupIdenArr);
        List<String> idensAndGroupIdens = new ArrayList<>();
        if(macroQuery.getIdenCodes() != null && macroQuery.getIdenCodes()!=""){
            String[] tempArr = macroQuery.getIdenCodes().split(",");
            idensAndGroupIdens.addAll(Arrays.asList(tempArr));
            re.setIdensAndGroupIdencodes(idensAndGroupIdens);
        }
        return re;
    }


    @RequestMapping(value = "/test",method = RequestMethod.POST)
    @ResponseBody
    public int test(){
        return macroTablemetaService.test();
    }
}
